package sample;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServer {
    public void Serer() {
        ServerSocket ss = null;
        Socket socket = null;
        InputStream is = null;
        FileOutputStream fos = null;
        OutputStream os = null;
        try {
            long start = System.currentTimeMillis();
            //1、创建服务端的serversocket，指明自己的端口号
            ss = new ServerSocket(8899);
            //2、调用accept方法接收客户端的socket
            socket = ss.accept();
            //3、获得输入流
            is = socket.getInputStream();
            //4、使用输出流将文件保存到本地
            fos = new FileOutputStream(new File("dataMonitoring.txt"));
            //5、读取文件，然后写出文件到本地
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            //6、服务端给予客户端反馈
            os = socket.getOutputStream();
            os.write("文件已收到！".getBytes());

            long end = System.currentTimeMillis();
            System.out.println("耗时" + (end - start));//耗时15 238
            System.out.println("已保存来自" + socket.getInetAddress().getHostName() + "的信息");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //7、资源关闭
            try {
                if (os != null)
                    os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fos != null)
                    fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (is != null)
                    is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (socket != null)
                    socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (ss != null)
                    ss.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
